from fastapi import APIRouter, Depends, HTTPException, status, UploadFile, File
from sqlalchemy.orm import Session
from sqlalchemy import or_
from typing import List, Optional
from datetime import date
from app.core.database import get_db
from app.core.deps import get_current_admin_user
from app.schemas.contract import ContractCreate, ContractUpdate, ContractResponse
from app.models.contract import Contract
from app.models.user import User
from app.services.oss_service import oss_service

router = APIRouter()

@router.get("", response_model=List[ContractResponse])
def get_contracts(
    skip: int = 0,
    limit: int = 100,
    customer_id: Optional[int] = None,
    start_date: Optional[date] = None,
    end_date: Optional[date] = None,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_admin_user)
):
    query = db.query(Contract)
    
    if customer_id:
        query = query.filter(Contract.customer_id == customer_id)
    if start_date:
        query = query.filter(Contract.contract_date >= start_date)
    if end_date:
        query = query.filter(Contract.contract_date <= end_date)
    
    contracts = query.offset(skip).limit(limit).all()
    return contracts

@router.post("", response_model=ContractResponse)
async def create_contract(
    contract: ContractCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_admin_user)
):
    existing = db.query(Contract).filter(
        Contract.contract_number == contract.contract_number
    ).first()
    if existing:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="合同编号已存在"
        )
    
    db_contract = Contract(**contract.model_dump())
    db.add(db_contract)
    db.commit()
    db.refresh(db_contract)
    return db_contract

@router.get("/{contract_id}", response_model=ContractResponse)
def get_contract(
    contract_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_admin_user)
):
    contract = db.query(Contract).filter(Contract.id == contract_id).first()
    if not contract:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="合同不存在"
        )
    return contract

@router.put("/{contract_id}", response_model=ContractResponse)
def update_contract(
    contract_id: int,
    contract_update: ContractUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_admin_user)
):
    contract = db.query(Contract).filter(Contract.id == contract_id).first()
    if not contract:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="合同不存在"
        )
    
    for key, value in contract_update.model_dump(exclude_unset=True).items():
        setattr(contract, key, value)
    
    db.commit()
    db.refresh(contract)
    return contract

@router.delete("/{contract_id}")
def delete_contract(
    contract_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_admin_user)
):
    contract = db.query(Contract).filter(Contract.id == contract_id).first()
    if not contract:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="合同不存在"
        )
    
    if contract.file_url:
        oss_service.delete_file(contract.file_url)
    
    db.delete(contract)
    db.commit()
    return {"message": "删除成功"}

